package com.app.manage.moudles.system.contoller;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollectionUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Controller
public class PageController {



    @GetMapping("toLogin")
    public String toLogin(){
        return "login";
    }



    @GetMapping("page/{pageIndex}")
    public String page(@PathVariable("pageIndex")String path)throws Exception{
        try {
            StpUtil.checkLogin();
        }catch (Exception e){
            System.err.println(e.getMessage());
            if(e instanceof NotLoginException){
                return "login";
            }
        }
        return path;
    }

    @GetMapping("page/{p1}/{p2}")
    public ModelAndView page2(@PathVariable("p1")String p1, @PathVariable("p2")String p2,
                              HttpServletRequest request)throws Exception{
        String url = "/"+p1+"/"+p2;
        ModelAndView mv  = new ModelAndView();
        try {
            if(!p1.equals("pushTask")){
                StpUtil.checkLogin();
            }
        }catch (Exception e){
            System.err.println(e.getMessage());
            if(e instanceof NotLoginException){
                mv.setViewName("login");
                return mv;
            }
        }

        mv.setViewName(url);

        Map<String,Object> paramMap = getParams(request);
        if(CollectionUtil.isNotEmpty(paramMap)){
            mv.addAllObjects(paramMap);
        }
        return mv;
    }

    private Map<String,Object> getParams(HttpServletRequest request){
        Map<String,Object> paramMap = new HashMap<>();
        Enumeration<String> parameterNames = request.getParameterNames();


        // 遍历所有参数名称
        while (parameterNames.hasMoreElements()) {
            String paramName = parameterNames.nextElement();
            String paramValue = request.getParameter(paramName);
            paramMap.put(paramName,paramValue);
        }
        return paramMap;
    }
}
